package org.zjx.db;

import org.zjx.common.bean.Npc;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class NpcDB {
    private static boolean isTableCreated = false;  // Flag to ensure the table is only created once
    private final SQLiteHelper dbHelper;

    public NpcDB() {
        dbHelper = SQLiteHelper.getSingleton();
        // Only create the table once when the instance is first created
        if (!isTableCreated) {
            createTable();
            isTableCreated = true;
        }
    }

    // Create table for Npc
    public void createTable() {
        String createTable = "CREATE TABLE IF NOT EXISTS npc (\n"
                + "    id INTEGER PRIMARY KEY AUTOINCREMENT,\n"
                + "    name TEXT NOT NULL,\n"
                + "    screenId INTEGER NOT NULL,\n"
                + "    roomId INTEGER NOT NULL,\n"
                + "    addresses TEXT\n"
                + ");";
        dbHelper.createTable(createTable);
    }

    // Insert a Npc record
    public void insert(Npc npc) {
        String sql = "INSERT INTO npc(name, screenId, roomId, addresses) VALUES(?, ?, ?, ?)";
        Object[] params = {
                npc.getName(),
                npc.getScreenId(),
                npc.getRoomId(),
                npc.getAddresses()
        };
        dbHelper.executeUpdate(sql, params);
    }

    // Update a Npc record
    public void update(Npc npc) {
        String sql = "UPDATE npc SET name = ?, screenId = ?, roomId = ?, addresses = ? WHERE id = ?";
        Object[] params = {
                npc.getName(),
                npc.getScreenId(),
                npc.getRoomId(),
                npc.getAddresses(),
                npc.getId()
        };
        dbHelper.executeUpdate(sql, params);
    }

    // Delete a Npc record by ID
    public void deleteById(int id) {
        String sql = "DELETE FROM npc WHERE id = ?";
        Object[] params = {id};
        dbHelper.executeUpdate(sql, params);
    }

    // Find Npc by ID
    public Npc findById(int id) {
        String sql = "SELECT * FROM npc WHERE id = ?";
        Object[] params = {id};
        List<Npc> npcs = dbHelper.executeQuery(sql, params, Npc.class);
        if (npcs.isEmpty()) return null;
        return npcs.get(0);
    }

    // Find Npc by Name
    public Npc findByName(String name) {
        String sql = "SELECT * FROM npc WHERE name = ?";
        Object[] params = {name};
        List<Npc> npcs = dbHelper.executeQuery(sql, params, Npc.class);
        if (npcs.isEmpty()) return null;
        return npcs.get(0);
    }

    public Npc findByNameAndScreenRoom(String name,int screenId,int roomId) {
        String sql = "SELECT * FROM npc WHERE name = ? AND screenId = ? AND roomId = ?";
        Object[] params = {name,screenId,roomId};
        List<Npc> npcs = dbHelper.executeQuery(sql, params, Npc.class);
        if (npcs.isEmpty()) return null;
        return npcs.get(0);
    }

    // Get all Npcs
    public List<Npc> findAll() {
        String sql = "SELECT * FROM npc";
        Object[] params = {};
        return dbHelper.executeQuery(sql, params, Npc.class);
    }

    // Paginated query for Npcs
    public Map<String, Object> findAllWithPagination(int pageNum, int pageSize) {
        int offset = (pageNum - 1) * pageSize;

        String sql = "SELECT * FROM npc LIMIT ? OFFSET ?";
        Object[] params = {pageSize, offset};
        List<Npc> npcs = dbHelper.executeQuery(sql, params, Npc.class);

        String countSql = "SELECT COUNT(*) FROM npc";
        Object[] countParams = {};
        List<Integer> totalRecordsList = dbHelper.executeQuery(countSql, countParams, Integer.class);
        int totalRecords = totalRecordsList.isEmpty() ? 0 : totalRecordsList.get(0);

        int totalPages = (int) Math.ceil((double) totalRecords / pageSize);

        Map<String, Object> result = new HashMap<>();
        result.put("npcList", npcs);
        result.put("totalRecords", totalRecords);
        result.put("totalPages", totalPages);
        result.put("currentPage", pageNum);

        return result;
    }

    // Clear all Npc data
    public void clearData() {
        dbHelper.clearData("npc");
    }

    // Drop the Npc table
    public void dropTable() {
        dbHelper.dropTable("npc");
    }
}
